package com.site.blog.my.core.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.site.blog.my.core.config.CommonLocalSetting;
import com.site.blog.my.core.constant.TbSystemConstant;
import com.site.blog.my.core.service.ConfigService;
import com.site.blog.my.core.util.FileUtil;
import com.site.blog.my.core.util.Result;
import com.site.blog.my.core.util.ResultGenerator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author xuwangcheng
 * @version 1.0.0
 * @description
 * @date 2020/12/17 14:20
 */
@Controller
@RequestMapping("/admin")
public class ThemeController {
    @Resource
    private ConfigService configService;
    @Resource
    private CommonLocalSetting commonLocalSetting;

    @GetMapping("/theme")
    public String themePage (HttpServletRequest request) {
        request.setAttribute("path", "theme");
        request.setAttribute("themeName", commonLocalSetting.getTheme());
        request.setAttribute("themeConfigurations", configService.getAllConfigs(commonLocalSetting.getTheme()));
        request.setAttribute("configurations", configService.getAllConfigs(TbSystemConstant.SYSTEM_CONFIG_TYPE));
        return "admin/theme";
    }

    @PostMapping("/theme/updateConfig")
    @ResponseBody
    public Result updateThemeConfig (@RequestBody Map<String, String> configs) {
        final AtomicInteger resultCount = new AtomicInteger(0);
        if (MapUtil.isNotEmpty(configs)) {
            CollUtil.forEach(configs, new CollUtil.KVConsumer<String, String>() {
                @Override
                public void accept(String key, String value, int index) {
                    if (StrUtil.isNotBlank(key)) {
                        resultCount.addAndGet(configService.updateConfig(key, value));
                    }
                }
            });
        }

        // 更新系统缓存的配置项
        if (resultCount.intValue() > 0) {
            commonLocalSetting.updateConfigs();
        }
        return ResultGenerator.genSuccessResult(resultCount.intValue() > 0);
    }
}
